package light.head.dao.inv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvSettlement;

import org.springframework.stereotype.Service;

/**
 * 结算方式
 * @author yy
 *
 */
@Service
public class InvSettlementDAO extends BaseDAO<InvSettlement, Integer>{
	private final static String sql_findAll = "FROM InvSettlement iu WHERE iu.oc = ?";
	
	
	public RESULT findByMap(Integer oc, Map<String,String> map, PageBean pb){
		if (oc == null ) return null;
		
		StringBuffer hql = new StringBuffer("FROM InvSettlement ist WHERE ist.oc = ?");
		List<Object> list = new ArrayList<Object>();
		
		list.add(oc);
		if (null != map) {
			String name = map.get(Parm.NAME);
			String cn = map.get(Parm.CN);
			String on = map.get(Parm.ON);
			String time1 = map.get(Parm.TIME1);
			String time2 = map.get(Parm.TIME2);
			String deleted = map.get(Parm.DELETED);
			
			if (isNotNull(name)) {
				list.add("%" + name + "%");
				hql.append(" AND ist.name LIKE ?");
			}if (isNotNull(cn)) {
				list.add("%" + cn + "%");
				hql.append(" AND ist.cu IN (SELECT u.code FROM UserInfo u WHERE u.realName LIKE ?)");
			}if (isNotNull(on)) {
				list.add("%" + on + "%");
				hql.append(" AND ist.oc IN (SELECT o.code FROM Organ o WHERE o.name LIKE ?)");
			}if (isNotNull(time1)) {
				list.add(DateUtils.getDateByStr(time1, null));
				hql.append(" AND ist.ct >= ?");
			}
			if (isNotNull(time2)) {
				list.add(DateUtils.getDateByStr(time2, null));
				hql.append(" AND ist.ct <= ?");
			}
			if (isNotNull(deleted)) {
				list.add(Boolean.parseBoolean(deleted));
				hql.append(" AND ist.deleted = ?");
			}
		}
		hql.append(" ORDER BY ist.code DESC");
		return findToPageBean(hql.toString(), pb, list);
	}
	public List<InvSettlement> findByNameOc(String name, Integer oc){
		if (name == null || oc == null) return null;
		StringBuffer hql = new StringBuffer("FROM InvSettlement de WHERE de.name = ? AND de.oc = ? ");
		List<Object> parm = new ArrayList<Object>();
		
		parm.add(name);
		parm.add(oc);
		
		return find(hql.toString(), parm.toArray());
	}
	
	public RESULT update(InvSettlement de) {
		if (null == de || de.getCode() == null) return null;
		InvSettlement db = this.get(de.getCode());
		if (null == db) return RESULT.NOT_FIND;
		
		boolean ok = false;
		if (!isNotNull(db.getName()) && isNotNull(de.getName()) || (!db.getName().equals(de.getName()))) {
			db.setName(de.getName());
			ok = true;
		}
		if (ok)
			return super.upd(db);
		
		return RESULT.SUCCESS;
	}
	
	public List<InvSettlement> findAll(Integer oc) {
		List<InvSettlement> list = find(sql_findAll, oc);
		return list;
	}
}
